<?php

namespace Manage\Http\Controllers;

use Illuminate\Support\Facades\Validator;
use Manage\DeviceRepair;
use Manage\Http\Requests;
use Manage\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Manage\Group;
use Manage\Base;
use Manage\Device;
use Input;
use View;
use Redirect;

class DeviceController extends Controller {

    /**
     * 设备信息查询
     * @param  string $group 指定小区
     * @return [type]        [description]
     */
    protected function info($group = 'all') {
        //分组获取
        $groupData = Group::getGroup();

        Base::dPush('groupData', $groupData, $this);

        //传入值传出验证
        Base::dPush('group', $group, $this);

        //数据获取
        $deviceData = Device::getDeviceByGroup($group);

        Base::dPush('deviceData', $deviceData, $this);
        return View::make('device.info', $this->data);
    }

    /**
     * 设备修改
     * @param  integer $id 设备ID
     * @return [type]      [description]
     */
    protected function edit($id = 0) {

        //设备查询
        if (Input::has('submit') && Input::has('notic')) {
            $id = Input::get('query');
            $type = Input::get('notic');

            if (empty($id)) {
                Base::dPush('error', 1, $this);
                Base::dPush('msg', '不存在的' . Input::get('notic') . '!', $this);
                return View::make('device.edit', $this->data);
            }

            if ($type == 'hardware_serial') {
                $id = Device::getDeviceIdByOther(Input::get('notic'), $id);
            }

            //验证设备所属
            if (Device::checkDevice($id) == false) {
                Base::dPush('error', 1, $this);
                Base::dPush('msg', '不存在的' . Input::get('notic') . '!', $this);
                return View::make('device.edit', $this->data);
            }
        }

        //设备修改
        if (Input::has('edit')) {
            $data = Input::all();

            array_pull($data, 'edit');

            $id = array_pull($data, 'devId');
            $phones = array_pull($data, 'phones');
            $memIds = array_pull($data, 'ids');
            $hardwareSerial = array_pull($data, 'hardware_serial');
            $group_id=array_pull($data, 'group');
            $town=array_pull($data, 'town');
            //基本数据修改
            Device::editInfoByDeviceId($id, $data);

            //绑定设备修改
            Device::editBindByDeviceId($id, $memIds, $phones, $hardwareSerial);

            //修改小区
            $agent_id=Device::getAgent($id)->id;

            Group::bindGroup($agent_id,$id,$group_id);

            Group::find($group_id)->update(array('location'=>$town));

            Base::dPush('error', 0, $this);
            Base::dPush('msg', '设备信息修改成功!', $this);
        }

        //设备手机搜索
        if (Input::has('phoneNum')) {
            $phone = Input::get('phoneNum');
            $id = Device::getDevIdByPhone($phone);
            Base::dPush('sphone', $phone, $this);
        }

        //获取设备信息
        $deviceData = Device::getDeviceInfo($id);

        //ID写入
        if (!empty($id)) {
            Base::dPush('devId', $id, $this);
        }

        Base::dPush('deviceData', $deviceData, $this);

        return View::make('device.edit', $this->data);
    }

    /**
     * 设备发放
     * @param  string $code [硬件序列号]
     * @return [type]       [description]
     */
    protected function bind($code = '') {
        //分组获取
        $groupData = Group::getGroup();

        Base::dPush('groupData', $groupData, $this);

        if (!empty($code)) {
            Base::dPush('code', $code, $this);
        }


        if (Input::has('bind')) {
            //设备绑定
            $result = Device::bindDevice($this->data['id'], Input::all());
            if ($result[0]==1) {
                Base::dPush('error', 0, $this);
                Base::dPush('msg', '设备发放成功!', $this);

                return View::make('device.bind', $this->data);
            } else {
                Base::dPush('error', 1, $this);
                Base::dPush('msg', $result[2], $this);

                return View::make('device.bind', $this->data);
            }
        }

        return View::make('device.bind', $this->data);
    }

    /**
     * 获取图表数据
     * @param int 设备ID
     * @return [type] [description]
     */
    protected function point($id = '') {

        if (Input::has('id')) {
            //获取面板详细数据
            $pointData = Device::getDataByDeviceId($_POST['id']);

            $pData = array();
            foreach ($pointData as $k => $val) {
                $pData[$k + 1] = $val->value;
            }

            return $pData;
        }
        return $_POST;
    }

    //获取设备充值日志
    public function getDeviceLog($entry) {
        //var_dump($entry);
        $data = Base::socketPost($_ENV['API_URI'] . "getDeviceLogs", array('device_id' => $entry));
        var_dump($data);
    }

    //设备返修
    public function getDeviceRepair() {
        return view('device.repare');
    }

    public function postDeviceRepair() {
        $data = Input::all();
        if (!isset($data['ids'])) {
            Base::dPush('error', 1, $this);
            Base::dPush('msg', '设备列表不能为空', $this);
            return view('device.repare')->with('data', $data)->with($this->data);
        }
        $data['device_ids'] = implode(',', $data['ids']);
        $data['agent_id'] = \Session::get('id');
        $devices = Device::whereIn('id', array($data['device_ids']))->get();
        if (!count($devices)) {
            return view('device.repare')->with('error', '设备错误');
        } else {
            \DB::update('update devices set status = 3 where id in(' . $data['device_ids'] . ')');
            $model = new DeviceRepair();
            if ($model->doSave($data)) {
                Base::dPush('msg', '保修成功', $this);
                return Redirect::to('deviceRepairs')->with('data', $data);
            } else {
                return view('device.repare')->with('error', '提交失败');
            }
        }
    }

    //设备返修列表
    public function getDeviceRepairs() {
        $datas = DeviceRepair::where('agent_id', \Session::get('id'))->orderBy('updated_at', 'desc')->paginate(10);
        $status = array('未受理', '已受理');
        return view('device.repares')->with('datas', $datas)->with('status', $status);
    }

    public function getDeviceRepairMsg($id) {
        $data = DeviceRepair::find($id);
        if($data['agent_id']!=\Session::get('id')){
            return Redirect::to('/');
        }
        switch ($data['status']) {
            case 0:
                $data['status'] = '未受理';
                break;
            case 1:
                $data['status'] = '已受理';
                break;
        }
        $data['device_ids']=explode(',',$data['device_ids']);
        $data['devices'] = Device::whereIn('devices.id', $data['device_ids'])
                ->leftJoin('member_device','member_device.device_id','=','devices.id')
                ->leftJoin('members','members.id','=','member_device.member_id')
                ->select('devices.*','members.username')->get();
        $devices=array();
        foreach ($data['devices'] as $value) {
           $devices[$value->id]['id']=$value->id; 
           $devices[$value->id]['communication_serial']=$value->communication_serial; 
           $devices[$value->id]['hardware_serial']=$value->hardware_serial;
           $devices[$value->id]['username'][]=$value->username;
        }
        $data['devices']=$devices;
        $data['agent']=\DB::table('agents')->find(\Session::get('id'));
        return view('device.repareMsg')->with('data', $data);
    }

    public function getDeviceSearch() {
        $data = Input::all();
        $devices = \DB::table('agents_device')
                ->leftJoin('devices', 'devices.id', '=', 'agents_device.device_id')
                ->where('agents_device.agent_id', \Session::get('id'))
                ->where('devices.status', '2');
        if ($data['id'] > 0) {
            $devices = $devices->where('devices.id', $data['id']);
        }
        if ($data['hardware_serial']) {
            $devices = $devices->where('devices.hardware_serial', $data['hardware_serial']);
        }
        if ($data['communication_serial']) {
            $devices = $devices->where('devices.communication_serial', $data['communication_serial']);
        }
        $devices = $devices->get();
        return (count($devices) ? json_encode($devices) : '0');
    }

}
